package longrise.phone.com.bjjt_henan.main;

import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.UiUtil;

import java.util.List;

import longrise.phone.com.bjjt_henan.Adapter.KeyResultAdapter;
import longrise.phone.com.bjjt_henan.Adapter.NavLinesAdapter;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.BDLocationManager;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.overlayutil.DrivingRouteOverlay;
import longrise.phone.com.bjjt_henan.Utils.overlayutil.MyDrivingRouteOverlay;
import longrise.phone.com.bjjt_henan.tinker.TinkerApplicationLike;
import longrise.phone.com.bjjt_henan.tinker.util.TinkerManager;

/**
 * 百度地图界面
 */
public class TrafficMapActivity extends Activity implements OnClickListener, TextWatcher {

    private MapView mapView;

    private BaiduMap baiduMap;

    private BroadcastReceiver mReceiver;

    private boolean updateFlag = true;//是否更新地图状态

    private ImageButton updateIBtn;//更新按钮

    private LatLng curLatLng;//当前位置的地理坐标点

    private String appCaseno;

    private int type;//0表示定位;1表示搜索;2表示周边事故;3表示充电站

    private LinearLayout trafficLayout;

    private TextView titleTV;

    private BitmapDescriptor sDescriptor;//覆盖物的图标

    private boolean firstFlag = true;

    private ImageView reverseIV;

    private TextView startTV;

    private TextView endTV;

    private Button clearBtn;

    private LinearLayout navLayout;

    private GridView linesGV;

    private NavLinesAdapter linesAdapter;

    private TextView navTV;

    private LinearLayout searchLayout;

    private EditText searchET;

    private ListView searchLV;

    private KeyResultAdapter keyAdapter;

    private Button backBtn;

    private DrivingRouteOverlay lineOverlay;//路径图

    private int flag;

    private BDLocationManager manager;

    private Dialog processDialog;

    private TextView cityTV;

    private String cityName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.trafficcondition_main);

        getData();
        initViews();
        initValues();
    }

    private void getData() {
        type = getIntent().getIntExtra("type", 0);
        appCaseno = getIntent().getStringExtra("appcaseno");
        if (type == 1) {
            sDescriptor = BitmapDescriptorFactory.fromResource(R.mipmap.icon_search_point);
        } else if (type == 2) {
            sDescriptor = BitmapDescriptorFactory.fromResource(R.mipmap.icon_accident_car);
        } else if (type == 3) {
            sDescriptor = BitmapDescriptorFactory.fromResource(R.mipmap.icon_charge_station);
        }
    }

    private void initViews() {
        titleTV = (TextView) findViewById(R.id.tv_title);
        findViewById(R.id.hn_btn_back).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        trafficLayout = (LinearLayout) findViewById(R.id.traffic_layout);
        updateIBtn = (ImageButton) findViewById(R.id.traffic_ibtn_location);
        updateIBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                requestLocation();
            }
        });
        mapView = (MapView) findViewById(R.id.bmapView);
        // 隐藏百度logo
        mapView.removeViewAt(1);
        baiduMap = mapView.getMap();
        //隐藏缩放按钮
        mapView.showZoomControls(false);
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        // 实时路况图层
        baiduMap.setTrafficEnabled(true);
        //隐藏指南针
        baiduMap.getUiSettings().setCompassEnabled(false);
        //监听触摸事件
        baiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        if (updateFlag) {
                            updateFlag = false;
                            updateIBtn.setImageResource(R.mipmap.icon_c11);
                        }
                        break;
                    default:
                        break;
                }
            }
        });

        // 注册广播
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
        mReceiver = new SDKReceiver();
        registerReceiver(mReceiver, iFilter);
    }

    /**
     * 监听 SDK key 验证以及网络异常广播
     */
    public class SDKReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action
                    .equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
                // key 验证失败，相应处理
                UiUtil.showToast(TrafficMapActivity.this, getResources()
                        .getString(R.string.key_error));
            } else if (action
                    .equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
                // 网络异常
                UiUtil.showToast(TrafficMapActivity.this, getResources()
                        .getString(R.string.net_error));
            }
        }
    }

    //更新地图状态
    private void requestLocation() {
        if (!updateFlag) {
            updateFlag = true;
            updateIBtn.setImageResource(R.mipmap.icon_c11_b);
            updateMap();
        }
    }

    // 以动画方式更新地图状态
    private void updateMap() {
        MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(curLatLng);
        baiduMap.animateMapStatus(status);
    }

    private void initValues() {
        setData();

        // 设置定位图标
        BitmapDescriptor descriptor = BitmapDescriptorFactory.fromResource(R.mipmap.icon_mark);
        baiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
                LocationMode.NORMAL, true, descriptor));
        //开始定位
        if (null == manager) {
            manager = new BDLocationManager(this);
            manager.setLocationListener(listener);
        }
        manager.startLocation();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 66) {
            manager.bdLocation();
        }
    }

    private BDLocationListener listener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null || mapView == null) {
                UiUtil.showToast(TrafficMapActivity.this, "定位失败，请检查定位权限和网络连接");
                return;
            }
            double curLatitude = location.getLatitude();
            double curLongitude = location.getLongitude();
            curLatLng = new LatLng(curLatitude, curLongitude);
            if (null != startTV && null == startTV.getTag()) {
                startTV.setTag(curLatLng);
            }
            cityName = location.getCity();
            if (null != cityTV) {
                cityTV.setText(cityName);
                cityTV.setVisibility(View.VISIBLE);
            }
            if (null != keyAdapter) {
                keyAdapter.setCityName(cityName);
            }
            // 显示定位位置
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    .direction(location.getDirection())
                    .latitude(curLatitude)
                    .longitude(curLongitude).build();
            baiduMap.setMyLocationData(locData);
            if (updateFlag) {
                updateMap();
            }

            if (type == 1 && firstFlag) {//查询附近的理赔中心
                firstFlag = false;
                searchCpsCenters();
            } else if (type == 2 && firstFlag) {//获取周边事故警示
                firstFlag = false;
                searchAccidentNotify();
            } else if (type == 3 && firstFlag) {//检索周边充电站
                firstFlag = false;
                searchCharge();
            }
        }

        @SuppressWarnings("unused")
        public void onReceivePoi(BDLocation poiLocation) {

        }
    };

    private void setData() {
        float scale = 3.0f;
        if (type == 0) {
            titleTV.setText("交通状况");
            scale = 15.0f;
            initNavView();
        } else if (type == 1) {
            titleTV.setText("附近理赔中心");
            trafficLayout.setVisibility(View.GONE);
            scale = 14.0f;
            //设置覆盖物的点击事件
            baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker marker) {
                    showInfoWindow(marker.getExtraInfo(), marker.getPosition());
                    return true;
                }
            });
        } else if (type == 2) {//周边事故
            titleTV.setVisibility(View.INVISIBLE);
            cityTV = (TextView) findViewById(R.id.tv_register);
            trafficLayout.setVisibility(View.GONE);
            scale = 15.0f;
            //设置覆盖物的点击事件
            baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker marker) {
                    showInfoWindow(marker.getExtraInfo(), marker.getPosition());
                    return true;
                }
            });
        } else if (type == 3) {
            titleTV.setText("附近充电站");
            trafficLayout.setVisibility(View.GONE);
            scale = 14.0f;
            //设置覆盖物的点击事件
            baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker marker) {
                    showInfoWindow(marker.getExtraInfo(), marker.getPosition());
                    return true;
                }
            });
        }
        // 设置地图缩放比例
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(scale);
        baiduMap.setMapStatus(msu);
    }

    //显示悬浮的详细信息
    private void showInfoWindow(Bundle bundle, final LatLng latLng) {
        if (null == bundle) {
            return;
        }
        View view = LayoutInflater.from(this).inflate(R.layout.baidumap_infowindow_view, null);
        TextView nameTV = (TextView) view.findViewById(R.id.overlay_name);
        TextView addTV = (TextView) view.findViewById(R.id.overlay_add);
        TextView phoneTV = (TextView) view.findViewById(R.id.overlay_phone);

        int offset = 0;
        if (type == 1) {
            nameTV.setText(bundle.getString("centername"));
            addTV.setText(bundle.getString("centeraddress"));
            phoneTV.setText("电话：" + bundle.getString("centerphone"));
            offset = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_search_point).getHeight();
        } else if (type == 2) {
            nameTV.setText("近1小时之内");
            addTV.setText(bundle.getString("imageaddress"));
            phoneTV.setVisibility(View.GONE);
            offset = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_accident_car).getHeight();
        } else if (type == 3) {
            ViewStub searchVS = (ViewStub) view.findViewById(R.id.overlay_vs_nav);
            searchVS.inflate();
            nameTV.setText(bundle.getString("name"));
            addTV.setText(bundle.getString("address"));
            phoneTV.setText("电话：" + bundle.getString("phonenum"));
            view.findViewById(R.id.overlay_btn_cancel).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    baiduMap.hideInfoWindow();
                }
            });
            view.findViewById(R.id.overlay_btn_confirm).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    baiduMap.hideInfoWindow();
                    startNavApp(latLng);
                }
            });
            offset = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_charge_station).getHeight();
        }
        // 显示悬浮的InfoWindow
        InfoWindow window = new InfoWindow(view, latLng, -offset);
        baiduMap.showInfoWindow(window);
    }

    //获取tinker的application代理类
    public TinkerApplicationLike getAppLike() {
        return (TinkerApplicationLike) TinkerManager.getTinkerApplicationLike();
    }

    //获取数据实体类
    public BaseApplication getAppData() {
        return (getAppLike() == null) ? null : getAppLike().getDataApp();
    }

    //查询理赔中心
    private void searchCpsCenters() {
        BaseApplication application = getAppData();
        String uid = application.getKckpName();
        String token = application.getToken();
        if (processDialog == null) {
            processDialog = UiUtil.showProcessDialog(this, "加载数据中...");
        } else {
            processDialog.show();
        }
        ApiImpI.getInstance(getApplication()).searchCenters(appCaseno, uid, token,
                new ApiImpI.RequestCallBack() {
                    @Override
                    public void onError(String error) {
                        if (processDialog != null && processDialog.isShowing()) {
                            processDialog.dismiss();
                        }
                        if (!TextUtils.isEmpty(error)) {
                            UiUtil.showToast(TrafficMapActivity.this, error);
                        }
                        firstFlag = false;
                    }

                    @Override
                    public void onSuccess(Object result) {
                        if (processDialog != null && processDialog.isShowing()) {
                            processDialog.dismiss();
                        }
                        if (null == mapView) {
                            return;
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        if ("1".equals(restate)) {
                            EntityBean[] dataBean = bean.getBeans("data");
                            if (dataBean != null) {
                                for (int x = 0; x < dataBean.length; x++) {
                                    showNearbyPosition(dataBean[x]);
                                }
                                return;
                            }
                        } else {
                            String redes = bean.getString("redes");
                            UiUtil.showToast(TrafficMapActivity.this, redes);
                        }
                    }
                });
    }

    //查询周边事故示警
    private void searchAccidentNotify() {
        BaseApplication application = getAppData();
        String uid = application.getKckpName();
        String token = application.getToken();
        String lat = String.valueOf(curLatLng.latitude);
        String lon = String.valueOf(curLatLng.longitude);
        if (processDialog == null) {
            processDialog = UiUtil.showProcessDialog(this, "加载数据中...");
        } else {
            processDialog.show();
        }
        ApiImpI.getInstance(getApplication()).searchAccidents(lat, lon, "60", uid, token,
                new ApiImpI.RequestCallBack() {
                    @Override
                    public void onError(String error) {
                        if (processDialog != null && processDialog.isShowing()) {
                            processDialog.dismiss();
                        }
                        if (!TextUtils.isEmpty(error)) {
                            UiUtil.showToast(TrafficMapActivity.this, error);
                        }
                        firstFlag = false;
                    }

                    @Override
                    public void onSuccess(Object result) {
                        if (processDialog != null && processDialog.isShowing()) {
                            processDialog.dismiss();
                        }
                        if (null == mapView) {
                            return;
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        if ("1".equals(restate)) {
                            EntityBean[] dataBean = bean.getBeans("data");
                            if (null == dataBean) {
                                showImgWindow();
                                return;
                            }
                            for (int x = 0; x < dataBean.length; x++) {
                                showAccidentPosition(dataBean[x]);
                            }
                        } else {
                            String redes = bean.getString("redes");
                            UiUtil.showToast(TrafficMapActivity.this, redes);
                        }
                    }
                });
    }

    private PoiSearch keySearch;

    private PoiNearbySearchOption keyOption;

    //查询充电站
    private void searchCharge() {
        if (keySearch == null) {
            keySearch = PoiSearch.newInstance();
            keySearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
                @Override
                public void onGetPoiResult(PoiResult res) {
                    if (res == null || res.getAllPoi() == null) {
                        //未找到相关结果
                        UiUtil.showToast(TrafficMapActivity.this, "检索位置失败，请检查定位权限和网络连接");
                        return;
                    }
                    List<PoiInfo> infoLists = res.getAllPoi();
                    for (int x = 0; x < infoLists.size(); x++) {
                        showChargeStation(infoLists.get(x));
                    }
                }

                @Override
                public void onGetPoiDetailResult(PoiDetailResult res) {

                }
            });
        }
        if (keyOption == null) {
            keyOption = new PoiNearbySearchOption().location(curLatLng).radius(10 * 1000);
        }
        keySearch.searchNearby(keyOption.keyword("充电站"));
    }

    //无事故显示安全提示
    private void showImgWindow() {
        Dialog dialog = new Dialog(this, R.style.AlertDialogStyle);
        dialog.setContentView(R.layout.baidumap_infowindow_picview);
        dialog.show();
    }

    //显示附近的充电站
    private void showChargeStation(PoiInfo info) {
        if (info == null) {
            return;
        }
        LatLng sLatLng = info.location;

        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions().position(sLatLng).icon(sDescriptor);
        //在地图上添加Marker，并显示
        Marker marker = (Marker) baiduMap.addOverlay(option);
        //添加详细信息
        Bundle bundle = new Bundle();
        bundle.putString("name", info.name);
        bundle.putString("address", info.address);
        bundle.putString("phonenum", info.phoneNum);

        marker.setExtraInfo(bundle);
    }

    //显示附近的事故位置
    private void showAccidentPosition(EntityBean pBean) {
        if (pBean == null) {
            return;
        }
        double sLatitude = Double.parseDouble(pBean.getString("imagelat"));
        double sLongitude = Double.parseDouble(pBean.getString("imagelon"));
        LatLng sLatLng = new LatLng(sLatitude, sLongitude);

        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions().position(sLatLng).icon(sDescriptor);
        //在地图上添加Marker，并显示
        Marker marker = (Marker) baiduMap.addOverlay(option);
        //添加详细信息
        Bundle bundle = new Bundle();
        bundle.putString("createtime", pBean.getString("createtime"));
        bundle.putString("imageaddress", pBean.getString("imageaddress"));
        marker.setExtraInfo(bundle);
    }

    //显示附近的理赔中心，设置地图的覆盖物
    private void showNearbyPosition(EntityBean pBean) {
        if (pBean == null) {
            return;
        }
        double sLatitude = Double.parseDouble(pBean.getString("gisp_x"));
        double sLongitude = Double.parseDouble(pBean.getString("gisp_y"));
        LatLng sLatLng = new LatLng(sLatitude, sLongitude);
        double distance = CommontUtils.getDistance(curLatLng, sLatLng);
        //显示10km以内的查询结果
        if (distance < 10 * 1000) {
            //构建MarkerOption，用于在地图上添加Marker
            OverlayOptions option = new MarkerOptions().position(sLatLng).icon(sDescriptor);
            //在地图上添加Marker，并显示
            Marker marker = (Marker) baiduMap.addOverlay(option);
            //添加详细信息
            Bundle bundle = new Bundle();
            bundle.putString("centername", pBean.getString("centername"));
            bundle.putString("centeraddress", pBean.getString("centeraddress"));
            bundle.putString("centerphone", pBean.getString("centerphone"));
            marker.setExtraInfo(bundle);
        }
    }

    //加载导航相关的视图
    private void initNavView() {
        //实例化起始位置视图
        ViewStub searchVS = (ViewStub) findViewById(R.id.traffic_vs_search);
        searchVS.inflate();
        reverseIV = (ImageView) findViewById(R.id.traffic_iv_reverse);
        startTV = (TextView) findViewById(R.id.traffic_tv_start);
        endTV = (TextView) findViewById(R.id.traffic_tv_end);
        clearBtn = (Button) findViewById(R.id.traffic_btn_clear);
        //实例化驾车路线视图
        navLayout = (LinearLayout) findViewById(R.id.traffic_layout_nav);
        linesGV = (GridView) findViewById(R.id.traffic_gv_lines);
        navTV = (TextView) findViewById(R.id.traffic_tv_nav);
        //实例化位置搜索视图
        searchLayout = (LinearLayout) findViewById(R.id.traffic_llayout_search);
        searchET = (EditText) findViewById(R.id.traffic_et_search);
        searchLV = (ListView) findViewById(R.id.traffic_lv_search);
        backBtn = (Button) findViewById(R.id.traffic_btn_back);

        //位置互换
        reverseIV.setOnClickListener(this);
        //开始位置
        startTV.setText("我的位置");
        startTV.setOnClickListener(this);
        //终点位置
        endTV.setOnClickListener(this);
        //清除驾车路线
        clearBtn.setOnClickListener(this);
        //显示驾车路线
        linesAdapter = new NavLinesAdapter(this);
        linesGV.setAdapter(linesAdapter);
        linesGV.setOnItemClickListener(new ItemClickImpI(0));
        //启动导航
        navTV.setOnClickListener(this);
        //搜索位置提示
        keyAdapter = new KeyResultAdapter(this);
        searchLV.setAdapter(keyAdapter);
        searchLV.setOnItemClickListener(new ItemClickImpI(1));
        searchET.addTextChangedListener(this);
        //返回
        backBtn.setOnClickListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        keyAdapter.refresh(s);
    }

    private static long lastClickTime;

    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 1000) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.traffic_iv_reverse://起始位置互换
                if (isFastClick()) {
                    return;
                }
                String start = startTV.getText().toString().trim();
                String end = endTV.getText().toString().trim();
                startTV.setText(end);
                endTV.setText(start);

                Object temp = startTV.getTag();
                startTV.setTag(endTV.getTag());
                endTV.setTag(temp);
                temp = null;

                if (null != startTV.getTag() && !TextUtils.isEmpty(start) && null != endTV.getTag() &&
                        !TextUtils.isEmpty(end)) {
                    searchNaLines();
                }
                break;
            case R.id.traffic_tv_start://搜索起始位置
                flag = 0;
                showSearchView(true);
                break;
            case R.id.traffic_tv_end://搜索终点位置
                flag = 1;
                showSearchView(true);
                break;
            case R.id.traffic_btn_clear://清除驾车路线
                navLayout.setVisibility(View.GONE);
                if (lineOverlay != null) {
                    lineOverlay.removeFromMap();
                }
                startTV.setText("我的位置");
                startTV.setTag(curLatLng);
                endTV.setText("");
                endTV.setTag(null);
                break;
            case R.id.traffic_tv_nav://启动导航
                LatLng latLng = (LatLng) endTV.getTag();
                if (latLng.latitude == curLatLng.latitude && latLng.longitude == curLatLng.longitude) {
                    latLng = (LatLng) startTV.getTag();
                }
                startNavApp(latLng);
                break;
            case R.id.traffic_btn_back://返回
                showSearchView(false);
                break;
            default:
                break;
        }
    }

    private void showSearchView(boolean isShow) {
        if (isShow) {//显示关键字搜索列表
            searchLayout.setVisibility(View.VISIBLE);
            searchET.setText("");
            searchET.requestFocus();
            CommontUtils.showSoftKeyBoard(this, searchET);
            keyAdapter.setInfoLists(null);
        } else {//隐藏界面
            searchLayout.setVisibility(View.GONE);
            CommontUtils.hideSoftKeyBoard(this);
        }
    }

    //启动导航App
    private void startNavApp(LatLng latLng) {
        try {
            String location = latLng.latitude + "," + latLng.longitude;
            Intent nav = new Intent();
            nav.setData(Uri.parse("baidumap://map/navi?location=" + location));
            startActivity(nav);
        } catch (ActivityNotFoundException e) {//未安装百度地图
            try {
                Intent gaode = new Intent("android.intent.action.VIEW",
                        Uri.parse("androidamap://navi?sourceApplication=快处快赔&lat=" +
                                latLng.latitude + "&lon=" + latLng.longitude + "&dev=0"));
                gaode.setPackage("com.autonavi.minimap");
                startActivity(gaode);
            } catch (Exception ex) {//未安装高德地图
                UiUtil.showToast(this, "未安装地图客户端，无法为您导航");
            }
        }
    }

    private RoutePlanSearch search;

    private DrivingRoutePlanOption option;

    //检索驾车导航路线
    private void searchNaLines() {
        if (search == null) {
            search = RoutePlanSearch.newInstance();
            search.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() {
                @Override
                public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

                }

                @Override
                public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

                }

                @Override
                public void onGetDrivingRouteResult(DrivingRouteResult result) {
                    //获取驾车线路规划结果
                    if (result == null || SearchResult.ERRORNO.RESULT_NOT_FOUND == result.error) {
                        UiUtil.showToast(TrafficMapActivity.this, "检索驾车路线失败，请检查定位权限和网络连接");
                        return;
                    }
                    linesGV.setNumColumns(result.getRouteLines().size());
                    linesAdapter.setLists(result.getRouteLines());
                    navLayout.setVisibility(View.VISIBLE);
                    //默认显示第一条线路
                    linesGV.performItemClick(null, 0, -1);
                }
            });
        }
        if (option == null) {
            option = new DrivingRoutePlanOption();
        }
        PlanNode sNode = PlanNode.withLocation((LatLng) startTV.getTag());
        PlanNode eNode = PlanNode.withLocation((LatLng) endTV.getTag());
        search.drivingSearch(option.from(sNode).to(eNode));
    }

    private class ItemClickImpI implements AdapterView.OnItemClickListener {

        private int type;

        public ItemClickImpI(int type) {
            this.type = type;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (type) {
                case 0://选择驾车路线
                    updateFlag = false;
                    updateIBtn.setImageResource(R.mipmap.icon_c11);
                    DrivingRouteLine data = linesAdapter.getLists().get(position);
                    if (lineOverlay == null) {
                        lineOverlay = new MyDrivingRouteOverlay(mapView.getMap());
                    } else {
                        lineOverlay.removeFromMap();
                    }
                    lineOverlay.setData(data);
                    lineOverlay.addToMap();
                    lineOverlay.zoomToSpan();
                    break;
                case 1://选择位置坐标
                    showSearchView(false);
                    PoiInfo select = keyAdapter.getInfoLists().get(position);
                    if (flag == 0) {
                        startTV.setText(select.name);
                        startTV.setTag(select.location);
                        if (null != endTV.getTag() && !TextUtils.isEmpty(endTV.getText().toString().trim())) {
                            searchNaLines();
                        }
                    } else if (flag == 1) {
                        endTV.setText(select.name);
                        endTV.setTag(select.location);
                        if (null != startTV.getTag() && !TextUtils.isEmpty(startTV.getText().toString().trim())) {
                            searchNaLines();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (manager != null) {
            manager.ondestroty();
        }
        // 关闭定位图层
        if (baiduMap != null) {
            baiduMap.setMyLocationEnabled(false);
        }
        if (mapView != null) {
            mapView.onDestroy();
        }
        mapView = null;
        unregisterReceiver(mReceiver);
        if (null != processDialog) {
            processDialog.dismiss();
            processDialog = null;
        }
        super.onDestroy();
    }

    @Override
    public void onResume() {
        mapView.onResume();
        // 启动服务
        if (manager != null) {
            manager.bdLocation();
        }
        super.onResume();
    }

    @Override
    public void onPause() {
        mapView.onPause();
        if (manager != null) {
            manager.stop();
        }
        super.onPause();
    }
}
